package com.auto.service.impl;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

import com.auto.annotation.AutoCode;
import com.common.CommonUtil;
import com.pojo.StateInfo;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.common.BackFileUtil;
import com.common.ClassTools;
import com.common.Global;

import freemarker.template.Configuration;

@Service("autoCode")
public class AutoCodeByFreeMarker implements com.auto.service.AutoCode {
	
	@Override
	public StateInfo run(boolean codeFlag) {
		long begin = System.currentTimeMillis();
		Logger.getLogger(this.getClass()).info("---开始代码生成---");
		Global.Send("---开始代码生成---");
		//简单的pojo对象
		Set<Class<?>> classes = ClassTools.getClasses(Global.PACKAGEOFPOJO);
		StateInfo stateInfo = new StateInfo();
		try {
			stateInfo = autoCode(classes,codeFlag);
		} catch (Exception e) {
			e.printStackTrace();
			stateInfo.setFlag(false);
			stateInfo.setMsg(e.getMessage());
		}
		long end = System.currentTimeMillis();

		Logger.getLogger(this.getClass()).info("---结束代码生成---");
		Global.Send("---结束代码生成---");

		Logger.getLogger(this.getClass()).info("总共花费了"+((end-begin)*0.001)+"秒");
		Global.Send("总共花费了"+((end-begin)*0.001)+"秒");
		return stateInfo;
	}

	private StateInfo autoCode(Set<Class<?>> classes,boolean code) throws Exception{
		Configuration cfg = FMConfiguration.getInstance();
		StateInfo stateInfo = new StateInfo();
		String funcName = "coder";
		if(!code) {
			funcName = "decoder";
		}
		for (Class<?> clas : classes){
			AutoCode auto = clas.getAnnotation(AutoCode.class);
			//没有写AUTO的注解的以及不愿意覆盖的，就不给于自动编写。
			if(auto == null || !auto.isOverride()) {
				continue;
			}
			boolean isOverride = auto.isOverride();
			Set<Class<?>> classesCoder = null;
			if("TREE".equals(auto.showWay().toUpperCase()) || CommonUtil.isEmpty(auto.showWay())) {
				classesCoder = ClassTools.getClasses(Global.PACKAGEOFCODER_TREE);
			}else if("LIST".equals(auto.showWay().toUpperCase())) {
				classesCoder = ClassTools.getClasses(Global.PACKAGEOFCODER_LIST);
			}
			//编写器
			/**
			 * 循环执行各个编写器。
			 */
			Global.Send("发现注解POJO类："+clas.getName());
			for(Class<?> clasCoder : classesCoder) {
				Method doMethod = null;
				doMethod = clasCoder.getMethod(funcName,Configuration.class,Map.class,boolean.class);
				Coder coder =(Coder)clasCoder.newInstance();
				Map<String,Object> root = coder.getRoot(clas);
				BackFileUtil.backFile(coder.getSrcPath(), coder.getTargetPath(), 
						root.get("paramName")==null?(String)root.get("className"):(String)root.get("paramName"), coder.getClassTail(), "F:\\PMback");
				StateInfo dealOneInfo = (StateInfo) doMethod.invoke(coder,cfg, root, isOverride);
				stateInfo.setFlag(stateInfo.getFlag()&&dealOneInfo.getFlag());
				if(!dealOneInfo.getFlag()) {
					Global.Send("当前解析出错，出错信息：："+dealOneInfo.getMsg());
					stateInfo.setMsg(stateInfo.getMsg()+";"+dealOneInfo.getMsg());
				}
			}
		}
		return stateInfo;
	}

	
}
